var express = require('express');
var router = express.Router();
var paymentDao = require('../dao/payment');
var paymentRoutes = module.exports;

var API = require('../libs/wxpay/WxPayApi.js');
var PayData = require('../libs/wxpay/WxPayDatabak.js');
/**
 * 订单生成
 * @param  openid
 * @param  item_id        购买项id
 * @param  num           份数
 *         url/payment/createOrder
 */

//小程序支付
function getJSAPIPay(d, par, cb) {
    var input = new PayData.WxPayDataBase();
    var out_trade_no = d.order_code;
    var total_fee = parseInt(d.pay_amount * 100);
    // var total_fee = 1;
    var body = d.name;
    var payApi = new API.WxPayApi();
    input.SetBody(body);                                                   //商品描述
    input.SetAttach(d.name);                                               //附加信息
    input.SetOut_trade_no(out_trade_no);                                   //订单号
    input.SetTotal_fee(total_fee);                                         //价格  单位分
    // input.SetNotify_url("http://sk92cm.natappfree.cc/qrcode/notify");   //回调地址
    input.SetSpbill_create_ip('127.0.0.1');                                //终端ip
    input.SetTrade_type("JSAPI");
    input.SetOpenid(par.openid);
    input.SetProduct_id(d.name);                                           //商品id   native  必传
    input.SetKeys();
    // var ip = req.get("X-Real-IP") || req.get("X-Forwarded-For") || req.ip;
    var ip = '127.0.0.1';
    payApi.unifiedOrder(input, 6, ip, function(result){
        if(result) {
            result = input.Init(result);
            if(result.return_code == 'SUCCESS') {
                var obj = {nonceStr: result.nonce_str, package:'prepay_id='+ result.prepay_id, timeStamp: new Date().getTime().toString()};
                var paySign = input.MakePaySign(obj);
                obj.paySign = paySign;
                cb(null, obj);
            } else {
                cb('订单生成失败， 请重试！');
            }
        } else {
            cb('参数有误！');
        }
    });
}
paymentRoutes.createOrder = function (req, res) {
    var par = paramAll(req);
    if(!par.item_id) return res.json(new ERR('购买项id不为空！', 400));
    if(!par.openid) return res.json(new ERR('openid不为空！', 400));
    if(!par.num) par.num = 1;
    paymentDao.createOrder(par, function(err, orderInfo) {
        if(err) return res.json(new ERR(err));
        getJSAPIPay(orderInfo, par, function(err, result) {
            if(err) return res.json(new ERR(err, 400));
            var obj = {
                timeStamp: result.timeStamp,
                nonceStr: result.nonceStr,
                package: result.package,
                signType: 'MD5',
                paySign: result.paySign
            };
            res.json(new PKG(obj));
        });
    })
}
router.post('/createOrder', paymentRoutes.createOrder);

/**
 * 微信支付成功 回调
 * @param
 *         url/payment/wxPayNotify
 */
paymentRoutes.wxPayNotify = function (req, res) {
    var key = 'GSIb3DQEBCwUAA4IBAQCB4bzF6wWznU7';
    var parseString = require('xml2js').parseString;
    parseString(req.rawBody, {explicitArray : false},function (err, result) {
        var notify = result.xml;
        var response = {
            return_code:"",
            return_msg:""
        };
        var input = new PayData.WxPayDataBase();
        var sign = input.IsWxReturn(notify, key);
        if(sign != notify.sign) {
            response={
                return_code:"FAIL",
                return_msg:notify.return_msg
            }
        } else if(notify.return_code == "SUCCESS" && notify.result_code =="SUCCESS"){
            var par = {};
            par.status = '13';
            par.payment = 'wxpay';
            par.pay_type = 'program';
            par.out_trade_no = notify.out_trade_no;
            paymentDao.tradeSuccess(par, function(e) {
                if(e) {
                    console.log(e);
                    return;
                } else {
                    console.log('success');
                }
            });
            response={
                return_code:"SUCCESS",
                return_msg:"OK"
            }
        } else {
            response={
                return_code:"FAIL",
                return_msg:notify.return_msg
            }
        }
        var resXML = '<xml><return_code><![CDATA['+response.return_code+']]></return_code> <return_msg><![CDATA['+response.return_msg+']]></return_msg> </xml>';
        res.send(resXML);
        res.end(resXML);
    });
}
router.post('/wxPayNotify', paymentRoutes.wxPayNotify);

/**
 * 续期
 * @param  id      地址id
 * @param  duration
 * @param  pay_amount
 * @param  openid
 *         url/payment/renewal
 */
paymentRoutes.renewal = function (req, res) {
    var par = paramAll(req);
    if(!par.id) return res.json(new ERR('地址id不为空！', 400));
    if(!par.duration) return res.json(new ERR('duration不为空！', 400));
    if(!par.pay_amount) return res.json(new ERR('支付金额不为空！', 400));
    paymentDao.renewal(par, function(err, result) {
        if(err) return res.json(new ERR(err, 400));
        res.json(new PKG(result));
    })
}
router.post('/renewal', paymentRoutes.renewal);

paymentRoutes.test = function (req, res) {
    var par = paramAll(req);
    if(!par.out_trade_no) return res.json(new ERR('out_trade_no不为空！', 400));
    par.status = '13';
    par.payment = 'wxpay';
    par.pay_type = 'program';
    paymentDao.tradeSuccess(par, function(err, result) {
        if(err) return res.json(new ERR(err, 400));
        res.json(new PKG(result));
    })
}
router.post('/test', paymentRoutes.test);

module.exports = router;